/*
 * @Author: your name
 * @Date: 2021-05-12 19:59:05
 * @LastEditTime: 2021-05-18 11:18:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blog-server\routes\bus.js
 */
const express = require('express')
const router = express.Router()
const User = require('../models/User')
const Article = require('../models/Article')
const createError = require('http-errors')
const assert = require('http-assert')
const app = require('../app')
const POPULATE_MAP = require('../plugins/POPULATE_MAP');

const { pagination } = require('../core/util/util')
const { modelName } = require('../models/User')

// /api/rest/:resource?query 
// /api/rest/users?query  users => User
// /api/rest/articles?query  articles => Article

//创建资源
router.post('/', async (req, res) => {
  try {
    const model = await req.Model.create(req.body)
    res.send(model)
  } catch (err) {
    next(createError(400))
  }

})

//更新资源
// /api/rest/:resource/:id?queryString...
router.put('/:id', async (req, res) => {
  const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
  res.send(model)
})

//删除资源
router.delete('/:id', async (req, res) => {
  await req.Model.findByIdAndDelete(req.params.id)
  res.send({
    errMsg: 'ok'
  })
})

//查询资源列表
router.get('/', async (req, res) => {
  const { options = {}, page = 1, size = 100, query = {}, dis = 8 } = req.body
  try {
    let result = await pagination({ model: req.Model, query, options, size, page, dis })
    res.send(result)
  } catch (err) {
    next(createError(422, '请求错误'))
  }
  // const queryOptions = req.body
  // console.log('req.body是', req);
  // const items = await req.Model.find()

  res.send(items)
})

//查询资源详情
router.get('/:id', async (req, res) => {
  try {
    let querys = await req.Model.findById(req.params.id)
    if (modelName in POPULATE_MAP) {
      let populates = POPULATE_MAP[modelName]
      for (let i = 0, item; item = populates[i++];) {
        querys = querys.populate(item['field'], item['select'])
      }
    }
    const result = await querys.exec()
    res.send(item)
  } catch (err) {
    console.log(err);
  }
})

module.exports = router
